package com.gupao.bingfa.work01;

import org.springframework.format.annotation.DateTimeFormat;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * @Description 使用线程后性能提升对比
 * @Author zhengshiling
 * @Date 2019/5/16 16:18
 * @Version 1.0
 **/

public class Demo1 {

    public static void main(String[] args) {
        //没有使用多线程，用时：3
        Date start = new Date();
        methodA();
        methodB();
        Date end = new Date();
        System.out.println("用时：" + (int) (end.getTime() - start.getTime()));

        //使用多线程后，用时：2
        CountDownLatch threadCount = new CountDownLatch(2);
        start = new Date();
        try {
            ThreadA a = new ThreadA(threadCount);
            ThreadB b = new ThreadB(threadCount);
            new Thread(a).start();
            new Thread(b).start();
            threadCount.await(); //等待所有子线程结束
            end = new Date();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("用时：" + (int) (end.getTime() - start.getTime()));
        }
    }

    public static void methodA() {
        try {
            Thread.sleep(1000);
            System.out.println("methodA end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void methodB() {
        try {
            Thread.sleep(2000);
            System.out.println("methodB end");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class ThreadA implements Runnable {
    CountDownLatch countDownLatch;

    public ThreadA(CountDownLatch threadCount) {
        this.countDownLatch = threadCount;
    }

    @Override
    public void run() {
        try {
            //countDownLatch.await();
            Thread.sleep(1000);
            System.out.println("methodA end");
            countDownLatch.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class ThreadB implements Runnable {
    CountDownLatch countDownLatch;

    public ThreadB(CountDownLatch threadCount) {
        this.countDownLatch = threadCount;
    }

    @Override
    public void run() {
        try {
            //countDownLatch.await();
            Thread.sleep(2000);
            System.out.println("methodB end");
            countDownLatch.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
